﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Newtonsoft.Json.Linq;
using ZBZH_Manage_Order.Models;
using ZBZH_Manage_Order.PublicMethod;
using Microsoft.AspNet.SignalR;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Web.UI;
using System.Configuration;
using System.Data;

namespace ZBZH_Manage_Order.Controllers.MerchantsSettings
{
    public class Order_FormController : Controller
    {
        //
        // GET: /Order_Form/

        ServiceReference1.Service1Client service = new ServiceReference1.Service1Client();


        public static List<Model.Order_Mer_T> shopList = new List<Model.Order_Mer_T>(); //当前商户全局变量


        public ActionResult Index()
        {

            Model.View_OperUser vo = null;
            vo = Session[SessionStorage.OperUser] as Model.View_OperUser;
            if (vo != null)
            {
                ViewBag.oe = vo.OperID;
            }
            else
            {
                return RedirectToAction("LoginPage", "Login");  //czx:修改为登录者的Session异常时，直接跳转到登录页面。20160718
            }

            return View();
        }

        /// <summary>
        /// 获取系统的增删查改的权限
        /// </summary>
        /// <returns></returns>
        public ActionResult getPower()
        {
            try
            {
                string[] PowerS = null;
                Models.ControlPower RetPower = new Models.ControlPower();
                Model.View_OperUser user = (Model.View_OperUser)Session[SessionStorage.OperUser];
                if (user != null)
                {
                    PowerS = user.RolePower.Split(',');//权限码
                    //拼接增删查改的权限
                    foreach (string pow in PowerS)
                    {
                        if (pow == "009007004")
                        { RetPower.Edit = 1; }
                    }
                }
                else
                {
                    return RedirectToAction("LoginPage", "Login");  //czx:修改为登录者的Session异常时，直接跳转到登录页面
                }
                return Json(RetPower);
            }
            catch (Exception ex)
            {
                return Json("操作异常：" + ex + "请联系管理员解决");
            }
        }

        /// <summary>
        /// 获取订单状态信息
        /// </summary>
        /// <returns></returns>
        public ActionResult getOrderFormType()
        {
            try
            {
                List<Model.Order_FormControl_T> list_Order_FormType = new List<Model.Order_FormControl_T>();//定义商品分类设置
                string result = service.GetFromConID(609, "009007", 0, GetYZM._YZM, 1);
                JObject searcho = JObject.Parse(result);//将服务返回的结果进行优化
                string bs = searcho["BS"].ToString();//获取返回结果是否正常标识
                if (bs == "1")
                {
                    IList<JToken> jieguo = searcho["rows"].Children().ToList();//解析返回的结果
                    list_Order_FormType = ParseClass<Model.Order_FormControl_T>.JsonList(jieguo);//解析返回的结果\
                    return Json(list_Order_FormType, JsonRequestBehavior.AllowGet);
                }
                else
                {
                    return Json("加载异常！");
                }
            }
            catch (Exception ex)
            {
                return Json("操作异常：" + ex + "请联系管理员解决");
            }
        }

        /// <summary>
        /// 订单状态信息
        /// </summary>
        /// <param name="MerID"></param>
        /// <returns></returns>
        public List<Model.Order_FormControl_T> OrderFormType(int tag)
        {
            List<Model.Order_FormControl_T> list_Order_FormType = new List<Model.Order_FormControl_T>();//定义订单状态
            string result = service.GetFromConID(512, "009007", tag, GetYZM._YZM, 1);
            JObject searcho = JObject.Parse(result);//将服务返回的结果进行优化
            string bs = searcho["BS"].ToString();//获取返回结果是否正常标识
            if (bs == "1")//返回结果正常
            {
                IList<JToken> jieguo = searcho["rows"].Children().ToList();//解析返回的结果
                if (jieguo.Count > 0)
                {
                    list_Order_FormType = ParseClass<Model.Order_FormControl_T>.JsonList(jieguo);//解析返回的结果\
                    //foreach (JToken item in jieguo)
                    //{
                    //    Model.Order_FormControl_T m = new Model.Order_FormControl_T();
                    //    m.ConID = int.Parse(item["ConID"].ToString());
                    //    m.ConText = item["ConText"].ToString();
                    //    m.NextCon = item["NextCon"].ToString();
                    //    list_Order_FormType.Add(m);
                    //}
                }
            }
            return list_Order_FormType;
        }

        /// <summary>
        /// 获取当前操作员拥有商户的权限
        /// </summary>
        /// <returns></returns>
        public ActionResult getMer(JqGridParam jqgridparam)
        {
            try
            {
                Page<Model.Order_Mer_T> page = new Page<Model.Order_Mer_T>();
                List<Model.Order_Mer_T> list = new List<Model.Order_Mer_T>();//定义商品分类设置
                Model.View_OperUser user = (Model.View_OperUser)Session[SessionStorage.OperUser];


                if (user == null)
                {
                    return RedirectToAction("LoginPage", "Login");  //czx:修改为登录者的Session异常时，直接跳转到登录页面
                }

                string result = service.GetMer(user.OperID, "", 1);
                JObject searcho = JObject.Parse(result);//将服务返回的结果进行优化
                string bs = searcho["BS"].ToString();//获取返回结果是否正常标识
                if (bs == "1")//返回结果正常
                {
                    IList<JToken> jieguo = searcho["rows"].Children().ToList();//解析返回的结果

                    list = ParseClass<Model.Order_Mer_T>.JsonList(jieguo);//解析返回的结果\

                    shopList = list;
                    //if (jieguo.Count > 0)
                    //{
                    //    foreach (JToken item in jieguo)
                    //    {
                    //        Model.Order_Mer_T m = new Model.Order_Mer_T();
                    //        m.MerID = item["MerID"].ToString();
                    //        m.MerName = item["MerName"].ToString();
                    //        m.MerAdr = item["MerAdr"].ToString();
                    //        m.MerCall = item["MerCall"].ToString();
                    //        m.MerTxt = item["MerTxt"].ToString();
                    //        list.Add(m);
                    //    }
                    //}
                    jqgridparam.records = list.Count;//查询的数据总数
                    var data = new
                    {
                        total = searcho["total"].ToString(),
                        rows = page.FindListPage(list, ref jqgridparam)//返回当前页的数据
                    };
                    return Json(data);
                }
                return Json(searcho["Msg"].ToString());
            }
            catch (Exception ex)
            {
                return Json("操作异常：" + ex + "请联系管理员解决");
            }
        }

        /// <summary>
        /// czx:获取是否有新的订单到达。20160725
        /// </summary>
        /// <param name="MerID">当前商户ID</param>  
        /// <returns></returns>
        public ActionResult getOrder(int OrderId)
        {
            try
            {
                string result = service.GetNewOrderId(OrderId, "", 1); //调用WebService，传入当前商户的最大ID的订单号。 返回格式：{"BS":"1","Msg":"查询成功","total":6,"rows":null}

                JObject searcho = JObject.Parse(result);//将服务返回的结果进行优化
                string bs = searcho["BS"].ToString();//获取返回结果是否正常标识
                if (bs == "1")//查询成功
                {
                    int total = Convert.ToInt32(searcho["total"].ToString());

                    if (total > 0)
                    {
                        return Json(total.ToString());  //有新的订单到达
                    }
                    else
                    {
                        return Json("-1");

                    }
                }


                return Json("-1");
            }
            catch (Exception ex)
            {
                return Json("-1");
            }

        }




        /// <summary>
        /// 获取商户的订单信息
        /// </summary>
        /// <param name="MerID"></param>
        /// <param name="jqgridparam"></param>
        /// <returns></returns>
        public ActionResult getgrid(string MerID, JqGridParam jqgridparam)
        {
            try
            {
                Page<Model.View_Order_Form> page = new Page<Model.View_Order_Form>();//分页类定义
                List<Model.View_Order_Form> list = new List<Model.View_Order_Form>();
                //string result = service.GetOrder_Form(jqgridparam.page, jqgridparam.rows, "", "", "", MerID, GetYZM._YZM, 1);
                //list = GetAllFrom(MerID);

                string result = service.GetOrder_Form(jqgridparam.page, jqgridparam.rows, "", "", "", MerID, GetYZM._YZM, 1); //czx:调用WebService获取订单数据
                JObject searcho = JObject.Parse(result);//将服务返回的结果进行优化
                string bs = searcho["BS"].ToString();//获取返回结果是否正常标识
                if (bs == "1")//返回结果正常
                {
                    IList<JToken> jieguo = searcho["rows"].Children().ToList();//解析返回的结果
                    if (jieguo.Count > 0)
                    {
                        list = ParseClass<Model.View_Order_Form>.JsonList(jieguo);//解析返回的结果\


                        foreach (Model.View_Order_Form item in list)
                        {
                            item.FormTime = DateTimeHelper.ToDate2(item.FormTime);
                            if (item.SenTime.Length == 14)
                            {
                                item.SenTime = DateTimeHelper.ToDate2(item.SenTime);
                            }
                        }
                    }
                    var data = new
                        {
                            total = searcho["total"].ToString(),
                            rows = list
                        };
                    return Json(data);
                }
                else
                {
                    var data = new
                    {
                        total = "0",
                        rows = list
                    };
                    return Json(data);
                }

                //if (list.Count > 0)
                //{
                //    jqgridparam.records = list.Count;//查询的数据总数
                //    var data = new
                //    {
                //        total = list.Count.ToString(),
                //        rows = page.FindListPage(list, ref jqgridparam)
                //    };
                //    return Json(data);
                //}
                //else
                //{
                //    var data = new
                //    {
                //        total = "0",
                //        rows = list
                //    };
                //    return Json(data);
                //}
            }
            catch (Exception ex)
            {
                return Json("操作异常：" + ex + "请联系管理员解决");
            }
        }

        /// <summary>
        /// 获取订单的所有商品信息
        /// </summary>
        /// <param name="MerID"></param>
        /// <param name="jqgridparam"></param>
        /// <returns></returns>
        public ActionResult getDishesgrid(string Dishes, JqGridParam jqgridparam)
        {
            try
            {
                Page<DishesForm> page = new Page<DishesForm>();//分页类定义
                List<DishesForm> list = new List<DishesForm>();
                string[] str_Dis = Dishes.Split('|');
                string[] str_DisID = str_Dis[0].Split(',');
                string[] str_DisName = str_Dis[1].Split(',');
                string[] str_DisNun = str_Dis[2].Split(',');
                string[] str_DisMon = str_Dis[3].Split(',');
                string[] str_DisInt = str_Dis[4].Split(',');
                for (int i = 0; i < str_DisID.Length; i++)
                {
                    DishesForm DishesForm = new DishesForm();
                    DishesForm.FormDishesID = str_DisID[i];  //菜品ID集合
                    DishesForm.FormDisheName = str_DisName[i]; // 菜品名称集合
                    DishesForm.FormDishesNun = int.Parse(str_DisNun[i]); //菜品数量集合
                    DishesForm.FormDishesMon = DataHelper.MoneyToYuang(str_DisMon[i]); //菜品原单价集合
                    if (str_DisInt.Length == 1)
                    {
                        DishesForm.FornDishesInt = "0";
                    }
                    else
                    {
                        DishesForm.FornDishesInt = str_DisInt[i];
                    }
                    if (DishesForm.FormDishesMon != "0")
                    { DishesForm.FornDishesCount = DataHelper.MoneyToYuang((int.Parse(str_DisMon[i]) * DishesForm.FormDishesNun).ToString()); }
                    else
                    { DishesForm.FornDishesCount = (int.Parse(str_DisInt[i]) * DishesForm.FormDishesNun).ToString(); }
                    list.Add(DishesForm);
                }
                if (list.Count > 0)
                {
                    jqgridparam.records = list.Count;//查询的数据总数
                    var data = new
                    {
                        total = list.Count.ToString(),
                        rows = page.FindListPage(list, ref jqgridparam)
                    };
                    return Json(data);
                }
                else
                {
                    var data = new
                    {
                        total = "0",
                        rows = list
                    };
                    return Json(data);
                }
            }
            catch (Exception ex)
            {
                return Json("操作异常：" + ex + "请联系管理员解决");
            }
        }

        /// <summary>
        /// 获取对应商户的所有订单
        /// </summary>
        /// <param name="MerID"></param>
        /// <returns></returns>
        //public string GetAllFrom(string MerID)
        public List<Model.View_Order_Form> GetAllFrom(string MerID)
        {
            List<Model.View_Order_Form> list = new List<Model.View_Order_Form>();
            //string result = service.GetOrder_Form(MerID, "", 1);  
            string result = service.GetOrder_Form(1, 10, "", "", "", MerID, GetYZM._YZM, 1);
            JObject searcho = JObject.Parse(result);//将服务返回的结果进行优化
            string bs = searcho["BS"].ToString();//获取返回结果是否正常标识
            if (bs == "1")//返回结果正常
            {
                IList<JToken> jieguo = searcho["rows"].Children().ToList();//解析返回的结果
                if (jieguo.Count > 0)
                {
                    list = ParseClass<Model.View_Order_Form>.JsonList(jieguo);//解析返回的结果\
                }
                return list;
            }
            else
            {
                return null;
            }
        }

        /// <summary>
        /// 获取下一个订单状态按钮
        /// </summary>
        /// <param name="FormBY"></param>
        /// <returns></returns>
        public ActionResult SeachOrderFormType(string FormBY)
        {
            try
            {
                List<Zcd> lsk = new List<Zcd>();//按钮list
                List<Model.Order_FormControl_T> DCDls = OrderFormType(1);//获取所有订单状态
                foreach (Model.Order_FormControl_T item in DCDls)
                {
                    if (item.ConID == FormBY.ToString())
                    {
                        if (item.NextCon != "" & item.NextCon != null)
                        {
                            string[] a = item.NextCon.Split(',');
                            //把可以选择下一个按钮组
                            foreach (string b in a)
                            {
                                Zcd z = new Zcd();
                                z.id = int.Parse(b);
                                foreach (Model.Order_FormControl_T i in DCDls)
                                {
                                    if (z.id.ToString() == i.ConID)
                                    {
                                        z.name = i.ConText;
                                        break;
                                    }
                                }
                                lsk.Add(z);
                            }
                        }
                        break;
                    }
                }
                var data = new
                {
                    total = lsk.Count,
                    rows = lsk//返回当前页的数据
                };
                return Json(data);
            }
            catch (Exception ex)
            {
                return Json("操作异常：" + ex + "请联系管理员解决");
            }
        }

        /// <summary>
        /// 更新商品上架信息
        /// </summary>
        /// <param name="Tag"></param>
        /// <param name="SaveShelves"></param>
        /// <returns></returns>
        public ActionResult UpdateOrder_Form(string FormID, string MerID, string FormBY, string IntBZ, string MerBZ)
        {
            try
            {
                string result = "";
                Model.View_OperUser user = (Model.View_OperUser)Session[SessionStorage.OperUser];//获取操作员

                if (user == null)
                {
                    return RedirectToAction("LoginPage", "Login");  //czx:修改为登录者的Session异常时，直接跳转到登录页面
                }

                #region 订单状态值
                List<Model.Order_FormControl_T> list_FormControl = OrderFormType(0);
                foreach (Model.Order_FormControl_T item in list_FormControl)
                {
                    if (FormBY == item.ConID)
                    {
                        if (item.NextCon != "" && item.NextCon != null)
                        {
                            string[] a;
                            a = item.NextCon.Split(',');
                        }
                    }
                }
                #endregion
                #region 备注
                if (MerBZ != "")
                {
                    IntBZ = IntBZ + ',' + DateTime.Now.ToShortDateString() + "商家补充备注：" + MerBZ;
                }
                #endregion
                result = service.SetOrder_Form(user.OperID, int.Parse(MerID), FormID, FormBY, IntBZ, GetYZM._YZM, 1);//设置上架信息
                JObject searcho = JObject.Parse(result);//将服务返回的结果进行优化
                string bs = searcho["BS"].ToString();//判断结果
                if (bs == "1")
                {
                    return Content(bs);
                }
                else
                {
                    return Content(searcho["Msg"].ToString());
                }

            }
            catch (Exception ex)
            {
                return Content("操作异常：" + ex + "请联系管理员解决");
            }
        }

        ///// <summary>
        ///// 加载派送员订单派送信息
        ///// </summary>
        ///// <param name="MerID"></param>
        ///// <param name="jqgridparam"></param>
        ///// <returns></returns>
        //public ActionResult Getgrid_TakerSend(string MerID, JqGridParam jqgridparam)
        //{
        //    try
        //    {
        //        List<Model.View_Order_Send_T> sen = new List<Model.View_Order_Send_T>();
        //        sen = service.GetGrid_Wiew_Send();
        //        return null;
        //    }
        //    catch(Exception ex)
        //    {
        //        return Content("操作异常：" + ex + "请联系管理员解决");
        //    }
        //}

        #region 查询订单

        public ActionResult searchForm(string MerID, string FormControl, string FormTimeS, string FormTimeE, JqGridParam jqgridparam)
        {
            try
            {

                Page<Model.View_Order_Form> page = new Page<Model.View_Order_Form>();
                List<Model.View_Order_Form> ls = new List<Model.View_Order_Form>();
                string result = service.GetOrder_Form(jqgridparam.page, jqgridparam.rows, FormTimeS, FormTimeE, FormControl, MerID, GetYZM._YZM, 1);
                JObject searcho = JObject.Parse(result);//将服务返回的结果进行优化
                string bs = searcho["BS"].ToString();//获取返回结果是否正常标识
                if (bs == "1")//返回结果正常
                {
                    IList<JToken> jieguo = searcho["rows"].Children().ToList();//解析返回的结果

                    ls = ParseClass<Model.View_Order_Form>.JsonList(jieguo);//解析返回的结果\
                    foreach (Model.View_Order_Form item in ls)
                    {
                        item.FormTime = DateTimeHelper.ToDate2(item.FormTime);
                        if (item.SenTime.Length == 14)
                        {
                            item.SenTime = DateTimeHelper.ToDate2(item.SenTime);
                        }
                    }
                }

                var data1 = new
                {
                    total = searcho["total"].ToString(),
                    rows = ls//返回当前页的数据 
                };
                return Json(data1);


                List<Model.View_Order_Form> newuc = new List<Model.View_Order_Form>();//定义一个新的对象，用于保存查询后的实体类列表
                FormTimeS = FormTimeS.Replace("-", "");
                FormTimeE = FormTimeE.Replace("-", "");

                int TimeS;
                int TimeE;
                if (FormTimeS != "" && FormTimeE != "" && FormControl == "")
                {
                    //int aa = int.Parse(FormControl);
                    //|| i.FormBY.Equals(aa)
                    TimeS = int.Parse(FormTimeS);
                    TimeE = int.Parse(FormTimeE);
                    var a = (from i in ls where (int.Parse(i.FormTime.Replace("/", "").Replace(" ", "").Replace(":", "").Substring(0, 8)) >= TimeS && int.Parse(i.FormTime.Replace("/", "").Replace(" ", "").Replace(":", "").Substring(0, 8)) <= TimeE) select i);
                    foreach (Model.View_Order_Form newForm in a)
                    {
                        newuc.Add(newForm);
                    }
                }
                else if (FormTimeS != "" && FormTimeE != "" && FormControl != "")
                {
                    int aa = int.Parse(FormControl);
                    TimeS = int.Parse(FormTimeS);
                    TimeE = int.Parse(FormTimeE);
                    var a = (from i in ls where (int.Parse(i.FormTime.Replace("/", "").Replace(" ", "").Replace(":", "").Substring(0, 8)) >= TimeS && int.Parse(i.FormTime.Replace("/", "").Replace(" ", "").Replace(":", "").Substring(0, 8)) <= TimeE) && i.FormBY.Equals(aa) select i);
                    foreach (Model.View_Order_Form newForm in a)
                    {
                        newuc.Add(newForm);
                    }
                }
                else
                {
                    int aa = int.Parse(FormControl);
                    newuc = (from i in ls where i.FormBY.Equals(aa) select i).ToList();
                    //foreach (View_Order_Form newForm in a)
                    //{
                    //    newuc.Add(newForm);
                    //}
                }



                var data = new
                {
                    total = searcho["total"].ToString(),
                    rows = ls//返回当前页的数据 
                };
                return Json(data);
            }
            catch (Exception)
            {
                return null;
            }
        }
        #endregion

        #region 获取订单下拉状态
        public ActionResult getFormBY(string FormID)
        {
            try
            {

                List<Model.Order_FormControl_T> List = new List<Model.Order_FormControl_T>();
                List<Zcd> lsk = new List<Zcd>();//按钮list
                string result = service.GetFromConID(int.Parse(FormID), "009007", 1, GetYZM._YZM, 1);
                JObject searcho = JObject.Parse(result);//将服务返回的结果进行优化
                string bs = searcho["BS"].ToString();//获取返回结果是否正常标识
                if (bs == "1")//返回结果正常
                {
                    IList<JToken> jieguo = searcho["rows"].Children().ToList();//解析返回的结果
                    List = ParseClass<Model.Order_FormControl_T>.JsonList(jieguo);//解析返回的结果
                    return Json(List, JsonRequestBehavior.AllowGet);

                }
                else
                {
                    return null;
                }

            }
            catch (Exception ex)
            {
                return Json("操作异常：" + ex + "请联系管理员解决");
            }
        }
        #endregion

        /// <summary>
        /// 定义从界面返回的订单信息
        /// </summary>
        public class SaveForm
        {
            public string FormID { get; set; }//订单ID
            public string MerID { get; set; }//商家ID
            public string FormBY { get; set; }//订单状态
            public string IntBZ { get; set; }//备注
            public string MerBZ { get; set; }//商家备注
        }

        /// <summary>
        /// 定义订单里的商品集合
        /// </summary>
        public class DishesForm
        {
            public string FormDishesID { get; set; }//商品ID
            public string FormDisheName { get; set; }//商品名称
            public int FormDishesNun { get; set; }//商品数量
            public string FormDishesMon { get; set; }//商品价格
            public string FornDishesInt { get; set; }//商品积分
            public string FornDishesCount { get; set; }//商品价格积分合计
        }

        /// <summary>
        ///设置按钮的id和名称
        /// </summary>
        public class Zcd
        {
            public int id { get; set; }
            public string name { get; set; }
        }
        public ActionResult no(string id)
        {
            IHubContext chat = GlobalHost.ConnectionManager.GetHubContext<Hubs.ChatHub>();
            string[] tm = id.Split('|');
            chat.Clients.All.addNewMessageToPage(tm[0], tm[1]);
            return null;
        }


        ///// <summary>
        ///// 订单消息
        ///// </summary>
        //public class View_Order_Form
        //{
        //    public string AccCall { get; set; }  //用户电话
        //    public int AccID { get; set; }  //用户ID
        //    public string AccName { get; set; }  //用户姓名
        //    public string ConText { get; set; }  // 
        //    public double DelFormMon { get; set; } //订单配送费用
        //    public double DelPackMon { get; set; } //订单包装费用
        //    public string FormAddress { get; set; } //送餐地点
        //    public double FormAllMon { get; set; } //订单合计总价
        //    public int FormBY { get; set; } //订单状态 
        //    public string FormDisheName { get; set; }  //菜品名称集合
        //    public string FormDishesID { get; set; }  //菜品ID集合
        //    public string FormDishesMon { get; set; } //菜品原单价集合
        //    public string FormDishesNun { get; set; } //菜品数量集合
        //    public string FormID { get; set; }  //订单ID
        //    public string FormMerID { get; set; } //商户ID
        //    public int FormPayInt { get; set; }  //消耗积分
        //    public double FormPayMon { get; set; } //实际支付价格
        //    public int FormPayType { get; set; } //支付类型
        //    public double FormPreMon { get; set; } //订单优惠价格
        //    public int FormPreW { get; set; } //优惠范围
        //    public int FormState { get; set; } //有效标识
        //    public string FormTime { get; set; } //订餐生成时间 
        //    public string FornDishesInt { get; set; }   //菜品积分集合
        //    public string IntBZ { get; set; } //备注
        //    public int IsEva { get; set; } //是否已评价
        //    public int IsPay { get; set; } //支付状态
        //    public int LastOper { get; set; } //最后操作员
        //    public string LastTime { get; set; } //最后操作时间
        //    public string MerName { get; set; }
        //    public string OperNum { get; set; }
        //    public string SenTime { get; set; } //送餐时间
        //}
    }
}
